from ninja import Router
from ninja.pagination import paginate
from django.shortcuts import get_object_or_404
from django.db import transaction
from typing import List

from .schemas import ScheduleIn, ScheduleOut
from ..models import Schedule

router = Router(tags=["班次管理"], auth=lambda request: request.user.is_staff)

@router.post("/schedules", response={201: ScheduleOut}, summary="创建班次")
@transaction.atomic
def create_schedule(request, payload: ScheduleIn):
    """
    创建新班次 (仅限管理员)
    
    - 需要管理员权限
    - 自动设置剩余座位数 = 总座位数
    """
    # 使用 model_dump() 替代弃用的 dict()
    data = payload.model_dump()
    schedule = Schedule.objects.create(
        **data,
        seats_available=data['seats_total'],  # 直接使用字典值
        created_by=request.user
    )
    return 201, schedule

@router.get("/schedules", response=List[ScheduleOut], summary="班次列表")
@paginate
def list_schedules(request):
    """查询所有班次 (分页支持)"""
    return Schedule.objects.all().order_by('departure_time')

@router.get("/schedules/{schedule_id}", response=ScheduleOut, summary="班次详情")
def get_schedule(request, schedule_id: int):
    """获取单个班次详细信息"""
    return get_object_or_404(Schedule, id=schedule_id)

@router.put("/schedules/{schedule_id}", response=ScheduleOut, summary="更新班次")
@transaction.atomic
def update_schedule(request, schedule_id: int, payload: ScheduleIn):
    """更新班次信息"""
    schedule = get_object_or_404(Schedule, id=schedule_id)
    # 使用 model_dump() 替代 dict()
    update_data = payload.model_dump(exclude_unset=True)  # 忽略未传字段
    for attr, value in update_data.items():
        setattr(schedule, attr, value)
    schedule.save()
    return schedule

@router.delete("/schedules/{schedule_id}", summary="删除班次")
def delete_schedule(request, schedule_id: int):
    """删除指定班次"""
    schedule = get_object_or_404(Schedule, id=schedule_id)
    schedule.delete()
    return 200, {"detail": "班次已删除"}